package com.topisv.tms.service.task;

import java.lang.management.ManagementFactory;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.task.TaskLocker;
import com.topisv.tms.repository.task.TaskLockerDao;

/**
 * 定时任务的调度服务类
 *  Date          Author       Version       Description
 * ----------------------------------------------------------
 *  2015-7-9      CC            1.0           Create
 */
@Component
public class ScheduledTaskService {
	@Autowired
	private TaskLockerDao taskLockerDao;
	private String node;

	/**
	 * 锁定当天任务为该节点执行
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void lock() {
		TaskLocker taskLocker = new TaskLocker();
		taskLocker.setDealIp(getNode());
		taskLocker.setLockTime(new Date());
		taskLockerDao.save(taskLocker);
	}

	/**
	 * 校验是否被当前接口锁定
	 * true已锁定 false未锁定
	 * @return boolean
	 */
	public boolean check() {
		return taskLockerDao.findLocked(getNode()) != null;
	}

	public String getNode() {
		if (node == null) {
			String name = ManagementFactory.getRuntimeMXBean().getName();
			node = name.substring(name.indexOf("@") + 1);
		}
		return node;
	}
}
